package com.jingdianjichi.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.jingdianjichi.auth.application.convert.AuthUserConvert;
import com.jingdianjichi.auth.application.dto.AuthUserDTO;
import com.jingdianjichi.auth.common.entity.Result;
import com.jingdianjichi.auth.domain.entity.AuthUserBO;
import com.jingdianjichi.auth.domain.redis.RedisUtil;
import com.jingdianjichi.auth.domain.service.AuthRoleDomainService;
import com.jingdianjichi.auth.domain.service.AuthUserDomainService;
import com.jingdianjichi.auth.infra.basic.mapper.AuthUserDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("/user/")
@Slf4j
public class AuthUserController {
    @Resource
    private AuthUserDomainService authUserService;
    private RedisUtil redisUtil;
    @Autowired
    private AuthRoleDomainService authRoleDomainService;
    @Autowired
    private AuthUserDomainService authUserDomainService;

    // 会话登录接口
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {
        try {
            if(log.isInfoEnabled()){
                log.info("validCode:{}", JSON.toJSONString(validCode));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(validCode),"验证码不能为空");
            SaTokenInfo saTokenInfo=authUserDomainService.doLogin(validCode);
            return Result.ok(saTokenInfo);
        }catch (Exception e){
            log.error("登陆报错error{}",e.getMessage());
            return Result.fail("登陆失败");
        }

    }
    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        // 此处仅作        模拟示例，真实项目需要从数据库中查询数据进行比对
        try {
            if(log.isInfoEnabled()){
                log.info("AuthUserDTO:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不得为空！");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"email不能为空！");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()),"密码不能为空！");
            AuthUserBO authUserBO= AuthUserConvert.INSTANCE.authUserDtoToAuthUserBo(authUserDTO);

            Boolean result=authUserService.register(authUserBO);
            return Result.ok(result);
        }catch (Exception e){
            log.info("新增失败：{}",e.getMessage());
            return  Result.fail("新增失败");
        }

    }

    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()){
                log.info("AuthUserDTO:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不得为空！");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"email不能为空！");
            AuthUserBO authUserBO= AuthUserConvert.INSTANCE.authUserDtoToAuthUserBo(authUserDTO);
            log.info("authuser BO:{}", JSON.toJSONString(authUserBO));
            Boolean result=authUserService.update(authUserBO);
            return Result.ok(result);
        }catch (Exception e){
            log.info("更新失败：{}",e.getMessage());
            return  Result.fail("更新失败");
        }

    }

    /**
     * 删除用户
     * @param authUserDTO
     * @return
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()){
                log.info("AuthUserDTO:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getId(),"id不得为空");
            AuthUserBO authUserBO= AuthUserConvert.INSTANCE.authUserDtoToAuthUserBo(authUserDTO);
            Boolean result=authUserService.delete(authUserBO);
            return Result.ok(result);
        }catch (Exception e){
            log.info("删除失败：{}",e.getMessage());
            return  Result.fail("删除失败");
        }

    }
    @PostMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()){
                log.info("AuthUserDTO:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getStatus(),"状态不得为空");
            Preconditions.checkNotNull(authUserDTO.getId(),"id不得为空");
            AuthUserBO authUserBO= AuthUserConvert.INSTANCE.authUserDtoToAuthUserBo(authUserDTO);
            Boolean result=authUserService.changeStatus(authUserBO);
            return Result.ok(result);
        }catch (Exception e){
            log.info("新增失败：{}",e.getMessage());
            return  Result.fail("更新失败");
        }

    }

    /**
     *
     * 获取个人信息页面
     * @param authUserDTO
     * @return
     */
    @RequestMapping("getUserInfo")
    public Result<AuthUserBO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()){
                log.info("AuthUserDTO:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名都不存在！");
            AuthUserBO authUserBO=AuthUserConvert.INSTANCE.authUserDtoToAuthUserBo(authUserDTO);
            AuthUserBO  authUserInfoBO = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO authUserInfoDto = AuthUserConvert.INSTANCE.authUserBoToAuthUserDto(authUserInfoBO);
            return Result.ok(authUserInfoDto);
        }catch (Exception e){
            log.info("error{}",e.getMessage());
            return Result.fail("获取失败");
        }
    }
    /**
     * 用户退出
     */
    @RequestMapping("logOut")
    public Result logOut(@RequestParam String username ) {
        try {
            if(log.isInfoEnabled()){
                log.info("AuthUserDTO:{}", JSON.toJSONString(username));
            }
                Preconditions.checkArgument(!StringUtils.isBlank(username),"用户名都不存在！");
                //登出
                StpUtil.logout(username);
                return Result.ok();

        }catch (Exception e){
            log.info("error{}",e.getMessage());
            return Result.fail("退出失败");
        }

    }

    /**
     * 上传头像
     * @return
     */

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
}
}